<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.hxci.pointmap.model.User" %>
<%@ page import="java.util.List" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 智慧农业管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
        }

        body {
            min-height: 100vh;
            background-color: #f8faf6;
            color: #334155;
        }

        /* 顶部导航栏 */
        .header {
            background: linear-gradient(135deg, #4caf50 0%, #81c784 100%);
            color: white;
            padding: 20px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            position: relative;
            z-index: 10;
        }

        .logo {
            display: flex;
            align-items: center;
        }

        .logo h1 {
            font-size: 24px;
            font-weight: 700;
        }

        .user-info {
            display: flex;
            align-items: center;
        }

        .user-info span {
            margin-right: 15px;
            font-weight: 500;
        }

        .user-info .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #f1f8e9;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #4caf50;
            font-weight: 600;
            cursor: pointer;
            position: relative;
        }

        .dropdown-menu {
            position: absolute;
            top: 100%;
            right: 0;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
            padding: 8px 0;
            min-width: 160px;
            z-index: 100;
            display: none;
            margin-top: 10px;
        }

        .dropdown-menu.show {
            display: block;
        }

        .dropdown-item {
            display: block;
            padding: 10px 20px;
            color: #333;
            text-decoration: none;
            transition: background-color 0.2s;
        }

        .dropdown-item:hover {
            background-color: #f1f8e9;
            color: #2e7d32;
        }

        .dropdown-divider {
            height: 1px;
            background-color: #e0e0e0;
            margin: 8px 0;
        }

        /* 主内容区域 */
        .main-content {
            display: flex;
            min-height: calc(100vh - 80px);
        }

        /* 左侧导航 */
        .sidebar {
            width: 220px;
            background: #e8f5e9;
            padding: 20px 0;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
            position: relative;
            z-index: 5;
        }

        .nav-group {
            margin-bottom: 30px;
        }

        .nav-title {
            color: #2e7d32;
            font-size: 16px;
            font-weight: 600;
            padding: 10px 25px;
            margin-bottom: 10px;
        }

        .nav-item {
            display: block;
            padding: 12px 25px;
            color: #334155;
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .nav-item:hover {
            background-color: #c8e6c9;
            color: #2e7d32;
        }

        .nav-item.active {
            background-color: #a5d6a7;
            color: #2e7d32;
            font-weight: 500;
            border-left: 4px solid #4caf50;
        }

        /* 内容区域 */
        .content {
            flex: 1;
            padding: 30px;
        }

        .page-title {
            font-size: 24px;
            font-weight: 600;
            color: #2e7d32;
            margin-bottom: 20px;
        }

        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            padding: 25px;
            margin-bottom: 25px;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .card-title {
            font-size: 18px;
            font-weight: 600;
            color: #334155;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-primary {
            background-color: #4caf50;
            color: white;
        }

        .btn-primary:hover {
            background-color: #388e3c;
        }

        .btn-danger {
            background-color: #f44336;
            color: white;
        }

        .btn-danger:hover {
            background-color: #d32f2f;
        }

        /* 表格样式 */
        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }

        th {
            background-color: #f1f8e9;
            font-weight: 600;
            color: #2e7d32;
        }

        tr:hover {
            background-color: #f9f9f9;
        }

        .actions {
            display: flex;
            gap: 10px;
        }

        .btn-small {
            padding: 5px 10px;
            font-size: 12px;
        }
        
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .modal-content {
            background: white;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }
        
        .modal-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #2e7d32;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #757575;
        }
        
        .modal-body {
            padding: 20px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #374151;
        }
        
        .form-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #4caf50;
            box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
        }
        
        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<!-- 顶部导航 -->
<div class="header">
    <div class="logo">
        <div class="logo-icon">🌱</div>
        <h1>智慧农业管理系统</h1>
    </div>
    <div class="user-info">
        <span>管理员</span>
        <div class="avatar" id="userAvatar">管</div>
        <div class="dropdown-menu" id="userDropdown">
            <a href="#" class="dropdown-item" onclick="showProfile()">个人设置</a>
            <div class="dropdown-divider"></div>
            <a href="#" class="dropdown-item" onclick="logout()">退出登录</a>
        </div>
    </div>
</div>

<!-- 主内容区 -->
<div class="main-content">
    <!-- 左侧导航 -->
    <div class="sidebar">
        <div class="nav-group">
            <div class="nav-title">系统导航</div>
            <a href="main.jsp" class="nav-item">系统首页</a>
            <a href="deviceManagement.jsp" class="nav-item">设备管理</a>
        </div>

        <div class="nav-group">
            <div class="nav-title">农业管理</div>
            <a href="environmentMonitor.jsp" class="nav-item">环境监测</a>
            <a href="pestControl.jsp" class="nav-item">病虫害防治</a>
            <a href="irrigationControl.jsp" class="nav-item">灌溉施肥</a>
        </div>

        <div class="nav-group">
            <div class="nav-title">系统设置</div>
            <a href="userServlet?actionType=list" class="nav-item active">用户管理</a>
            <a href="system_config.jsp" class="nav-item">系统配置</a>
            <a href="tech.jsp" class="nav-item">技术支持</a>
            <a href="we.jsp" class="nav-item">关于我们</a>
        </div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
        <h1 class="page-title">用户管理</h1>

        <div class="card">
            <div class="card-header">
                <h2 class="card-title">用户列表</h2>
                <button class="btn btn-primary" onclick="showAddUserModal()">添加用户</button>
            </div>

            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>登录账号</th>
                            <th>姓名</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <% 
                        List<User> userList = (List<User>) request.getAttribute("userList");
                        if (userList != null) {
                            for (User user : userList) {
                        %>
                        <tr>
                            <td><%= user.getId() %></td>
                            <td><%= user.getLoginAccount() %></td>
                            <td><%= user.getUserName() != null ? user.getUserName() : "-" %></td>
                            <td><%= user.getCreateTime() %></td>
                            <td class="actions">
                                <button class="btn btn-primary btn-small" onclick="editUser(<%= user.getId() %>)">编辑</button>
                                <button class="btn btn-danger btn-small" onclick="deleteUser(<%= user.getId() %>)">删除</button>
                            </td>
                        </tr>
                        <%
                            }
                        }
                        %>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 添加用户模态框 -->
<div class="modal" id="addUserModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">添加用户</h3>
            <button class="modal-close" onclick="closeAddUserModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="addUserForm">
                <div class="form-group">
                    <label class="form-label">登录账号</label>
                    <input type="text" id="addLoginAccount" name="loginAccount" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">登录密码</label>
                    <input type="password" id="addLoginPwd" name="loginPwd" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">确认密码</label>
                    <input type="password" id="addConfirmPwd" name="confirmPwd" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label">用户姓名</label>
                    <input type="text" id="addUserName" name="userName" class="form-input">
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" onclick="closeAddUserModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addUser()">添加</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑用户模态框 -->
<div class="modal" id="editUserModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">编辑用户</h3>
            <button class="modal-close" onclick="closeEditUserModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="editUserForm">
                <input type="hidden" id="editUserId" name="id">
                <div class="form-group">
                    <label class="form-label">登录账号</label>
                    <input type="text" id="editLoginAccount" name="loginAccount" class="form-input" readonly>
                </div>
                <div class="form-group">
                    <label class="form-label">用户姓名</label>
                    <input type="text" id="editUserName" name="userName" class="form-input">
                </div>
                <div class="form-group">
                    <label class="form-label">修改密码（留空则不修改）</label>
                    <input type="password" id="editLoginPwd" name="loginPwd" class="form-input">
                </div>
                <div class="form-group">
                    <label class="form-label">确认新密码</label>
                    <input type="password" id="editConfirmPwd" name="confirmPwd" class="form-input">
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" onclick="closeEditUserModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateUser()">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // 用户下拉菜单功能
    document.addEventListener('DOMContentLoaded', function() {
        const userAvatar = document.getElementById('userAvatar');
        const userDropdown = document.getElementById('userDropdown');

        // 点击头像显示/隐藏下拉菜单
        userAvatar.addEventListener('click', function(e) {
            e.stopPropagation();
            userDropdown.classList.toggle('show');
        });

        // 点击页面其他地方隐藏下拉菜单
        document.addEventListener('click', function() {
            userDropdown.classList.remove('show');
        });

        // 阻止下拉菜单内部点击事件冒泡
        userDropdown.addEventListener('click', function(e) {
            e.stopPropagation();
        });
    });

    // 显示个人设置
    function showProfile() {
        window.location.href = 'profile.jsp';
    }

    // 退出登录
    function logout() {
        if (confirm('确定要退出登录吗？')) {
            fetch('logout', {
                method: 'POST'
            })
            .then(response => {
                if (response.ok) {
                    window.location.href = 'login.jsp';
                } else {
                    alert('退出登录失败，请稍后再试');
                }
            })
            .catch(error => {
                console.error('退出登录失败:', error);
                alert('退出登录失败，请稍后再试');
            });
        }
    }

    // 显示添加用户模态框
    function showAddUserModal() {
        document.getElementById('addUserModal').style.display = 'flex';
        document.getElementById('addUserForm').reset();
    }
    
    // 关闭添加用户模态框
    function closeAddUserModal() {
        document.getElementById('addUserModal').style.display = 'none';
    }
    
    // 添加用户
    function addUser() {
        const loginAccount = document.getElementById('addLoginAccount').value.trim();
        const loginPwd = document.getElementById('addLoginPwd').value;
        const confirmPwd = document.getElementById('addConfirmPwd').value;
        const userName = document.getElementById('addUserName').value.trim();
        
        // 表单验证
        if (!loginAccount) {
            alert('请输入登录账号');
            return;
        }
        
        if (!loginPwd) {
            alert('请输入登录密码');
            return;
        }
        
        if (loginPwd.length < 6) {
            alert('密码长度不能少于6位');
            return;
        }
        
        if (loginPwd !== confirmPwd) {
            alert('两次输入的密码不一致');
            return;
        }
        
        // 构建表单数据
        const formData = new URLSearchParams();
        formData.append('actionType', 'register');
        formData.append('loginAccount', loginAccount);
        formData.append('loginPwd', loginPwd);
        formData.append('userName', userName || '普通用户');
        
        // 发送请求
        fetch('userServlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('用户添加成功');
                closeAddUserModal();
                // 刷新页面
                window.location.reload();
            } else {
                alert('添加失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('添加失败，请稍后再试');
        });
    }
    
    // 编辑用户
    function editUser(userId) {
        // 获取用户信息
        fetch(`userServlet?actionType=getUserById&id=${userId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 填充表单
                document.getElementById('editUserId').value = data.user.id;
                document.getElementById('editLoginAccount').value = data.user.loginAccount;
                document.getElementById('editUserName').value = data.user.userName || '';
                
                // 显示模态框
                document.getElementById('editUserModal').style.display = 'flex';
            } else {
                alert('获取用户信息失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('获取用户信息失败，请稍后再试');
        });
    }
    
    // 关闭编辑用户模态框
    function closeEditUserModal() {
        document.getElementById('editUserModal').style.display = 'none';
    }
    
    // 更新用户
    function updateUser() {
        const userId = document.getElementById('editUserId').value;
        const userName = document.getElementById('editUserName').value.trim();
        const loginPwd = document.getElementById('editLoginPwd').value;
        const confirmPwd = document.getElementById('editConfirmPwd').value;
        
        // 如果输入了新密码，验证密码
        if (loginPwd) {
            if (loginPwd.length < 6) {
                alert('密码长度不能少于6位');
                return;
            }
            
            if (loginPwd !== confirmPwd) {
                alert('两次输入的密码不一致');
                return;
            }
        }
        
        // 构建表单数据
        const formData = new URLSearchParams();
        formData.append('actionType', 'updateProfile');
        formData.append('id', userId);
        formData.append('userName', userName);
        
        if (loginPwd) {
            formData.append('newPassword', loginPwd);
            formData.append('oldPassword', ''); // 这里简化处理，实际应要求输入原密码
        }
        
        // 发送请求
        fetch('userServlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (data.needReLogin) {
                    alert('密码已修改，请重新登录');
                    window.location.href = 'login.jsp';
                } else {
                    alert('用户信息更新成功');
                    closeEditUserModal();
                    // 刷新页面
                    window.location.reload();
                }
            } else {
                alert('更新失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('更新失败，请稍后再试');
        });
    }
    
    // 删除用户
    function deleteUser(userId) {
        if (confirm('确定要删除该用户吗？此操作不可恢复！')) {
            fetch(`userServlet?actionType=deleteUser&id=${userId}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('用户删除成功');
                    // 刷新页面
                    window.location.reload();
                } else {
                    alert('删除失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除失败，请稍后再试');
            });
        }
    }
</script>
</body>
</html>
